package top.haijunit.springboot.bucket.springsecurity02.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import top.haijunit.mark.common.core.Result;
import top.haijunit.mark.common.core.utils.ResponseUtil;
import top.haijunit.springboot.bucket.springsecurity02.security.TokenAuthFilter;
import top.haijunit.springboot.bucket.springsecurity02.security.TokenLoginFilter;
import top.haijunit.springboot.bucket.springsecurity02.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 百旺张
 * @Date 2021/11/11
 * @Description
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    /** 不进行认证的路径，可以直接访问 */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/", "/favicon.ico", "/ui/**", "/**/*.html", "/**/*.css", "/**/*.js");
    }

    /** 配置设置 */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 异常返回处理
        http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
            // 认证失败
            ResponseUtil.write(response, Result.failed("您还没有登录，请登录").addData("uri", request.getRequestURI()).addData("error", authException.getMessage()));
        }).accessDeniedHandler((request, response, accessDeniedException) -> {
            // 无权访问异常处理
            ResponseUtil.write(response, Result.failed("您无权访问").addData("uri", request.getRequestURI()).addData("error", accessDeniedException.getMessage()));
        });
        // url 权限控制
        http.authorizeRequests().antMatchers("/hello").hasAuthority("hello").anyRequest().authenticated();
        // 登出操作
        http.logout().logoutUrl("/logout").addLogoutHandler((request, response, authentication) -> {
            // TODO 退出登录，可操作销毁token
            ResponseUtil.write(response, Result.ok());
        });
        // 禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 自定义登录Filter
        http.addFilter(new TokenLoginFilter(authenticationManager()));
        // token验证的Filter
        http.addFilter(new TokenAuthFilter(authenticationManager(), userService));
        // 关闭csrf防护
        http.csrf().disable();
        // 支持SAMEORIGIN的设置方式
        http.headers().frameOptions().sameOrigin();
    }

    /** 配置认证 数据库认证 */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}
